package com.ukefu.webim.web.handler.admin.mycallcenter;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.ukefu.webim.web.model.Extention;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.util.Menu;
import com.ukefu.webim.service.repository.ExtentionRepository;
import com.ukefu.webim.service.repository.MediaRepository;
import com.ukefu.webim.service.repository.PbxHostRepository;
import com.ukefu.webim.service.repository.ServiceAiRepository;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.PbxHost;

@Controller
@RequestMapping("/admin/mycallcenter")
public class MyCallCenterResourceController extends Handler{
	
	@Autowired
	private PbxHostRepository pbxHostRes ;
	
	@Autowired
	private ExtentionRepository extentionRes;
	
	
	@RequestMapping(value = "/resource")
    @Menu(type = "callcenter" , subtype = "mycallcenter" , access = false )
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid final String hostid) {
		PbxHost pbxHost = pbxHostRes.findById(hostid) ;
		//map.addAttribute("pbxHostList" , pbxHostList);
		final String orgi = super.getOrgi(request);
		if(pbxHost != null){
			map.addAttribute("pbxHost" , pbxHost);

			Page<Extention> extentionPageList = extentionRes.findAll(new Specification<Extention>() {
				@Override
				public Predicate toPredicate(Root<Extention> root,
											 CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();
					list.add(cb.equal(root.get("hostid").as(String.class), hostid));
					list.add(cb.equal(root.get("orgi").as(String.class),orgi));
					Predicate[] p = new Predicate[list.size()];
					return cb.and(list.toArray(p));
				}
			}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.ASC, "extention","createtime"));
			map.addAttribute("extentionList" , extentionPageList.getContent());
			map.addAttribute("extentionPageList" , extentionPageList);
		}
		map.addAttribute("ismy" , true);
		return request(super.createAdminTempletResponse("/admin/mycallcenter/resource/index"));
    }
	
}
